package com.fanfan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fanfan.enums.AppHttpCodeEnum;
import com.fanfan.exception.SystemException;
import com.fanfan.pojo.Menu;
import com.fanfan.pojo.domain.ResponseResult;
import com.fanfan.pojo.vo.MenuDto;
import com.fanfan.pojo.vo.MenuVo;
import com.fanfan.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("system/menu")
public class MenuController {
    @Autowired
    MenuService menuService;
    @GetMapping("/list")
    public ResponseResult listMenu(MenuVo menuVo){
        return menuService.listMenu(menuVo);
    }
    @PostMapping
    public ResponseResult addMenu(@RequestBody Menu menu){
        menuService.save(menu);
        return ResponseResult.okResult();
    }
    @GetMapping("/{id}")
    public ResponseResult queryMenu(@PathVariable Long id){
        Menu menu = menuService.getById(id);
        return ResponseResult.okResult(menu);
    }
    @PutMapping
    public ResponseResult reviseMenu(@RequestBody Menu menu){
        if (menu.getParentId()!=menu.getId()){
        menuService.getBaseMapper().updateById(menu);
        return ResponseResult.okResult();
        }else {
            throw new SystemException(AppHttpCodeEnum.REVISE_ERROR);
        }
    }
    @DeleteMapping("/{menuId}")
    public ResponseResult deleteMenu(@PathVariable Long menuId){
        LambdaQueryWrapper<Menu> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getParentId,menuId);
        Integer count = menuService.getBaseMapper().selectCount(queryWrapper);
        if (count==0) {
            menuService.getBaseMapper().deleteById(menuId);
            return ResponseResult.okResult();
        }else {
            throw new SystemException(AppHttpCodeEnum.DELETE_ERROR);
        }
    }
    @GetMapping("/treeselect")
    public ResponseResult treeSelectMenu(){
        List<MenuDto> menuDtos = menuService.treeSelectMenu();
        return ResponseResult.okResult(menuDtos);
    }
    @GetMapping("/roleMenuTreeselect/{id}")
    public ResponseResult roleMenuTreeSelect(@PathVariable Long id){
        return menuService.roleMenuTreeSelect(id);
    }
}







